package neatlogic.module.change.api;

import neatlogic.framework.auth.core.AuthAction;
import neatlogic.framework.common.constvalue.ApiParamType;
import neatlogic.framework.common.constvalue.GroupSearch;
import neatlogic.framework.process.auth.PROCESS_BASE;
import neatlogic.framework.restful.annotation.Description;
import neatlogic.framework.restful.annotation.Input;
import neatlogic.framework.restful.annotation.OperationType;
import neatlogic.framework.restful.annotation.Param;
import neatlogic.framework.restful.constvalue.OperationTypeEnum;
import neatlogic.framework.restful.core.privateapi.PrivateApiComponentBase;
import neatlogic.framework.change.constvalue.ChangeOperationType;
import neatlogic.module.change.dao.mapper.ChangeMapper;
import neatlogic.framework.change.dto.ChangeVo;
import neatlogic.framework.change.exception.ChangeNoPermissionException;
import neatlogic.framework.change.exception.ChangeNotFoundException;
import neatlogic.module.change.service.ChangeService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional
@AuthAction(action = PROCESS_BASE.class)
@OperationType(type = OperationTypeEnum.OPERATE)
public class ChangeStartApi extends PrivateApiComponentBase {

    @Autowired
    private ChangeMapper changeMapper;

    @Autowired
    private ChangeService changeService;

    @Override
    public String getToken() {
        return "change/start";
    }

    @Override
    public String getName() {
        return "nmca.changestartapi.getname";
    }

    @Override
    public String getConfig() {
        return null;
    }

    @Input({
            @Param(name = "changeId", type = ApiParamType.LONG, isRequired = true, desc = "term.change.changeid"),
            @Param(name = "source", type = ApiParamType.STRING, desc = "common.source")
    })
    @Description(desc = "nmca.changestartapi.getname")
    @Override
    public Object myDoService(JSONObject jsonObj) throws Exception {
        Long changeId = jsonObj.getLong("changeId");
        ChangeVo changeVo = changeMapper.getChangeById(changeId);
        if (changeVo == null) {
            throw new ChangeNotFoundException(changeId);
        }
        /** 获取当前变更锁 **/
        changeMapper.getChangeLockById(changeId);
        String owner = changeMapper.getChangeUserByChangeId(changeId);
        if (StringUtils.isNotBlank(owner)) {
            changeVo.setOwner(GroupSearch.USER.getValuePlugin() + owner);
        }
        if (!changeService.isStartableChange(changeVo)) {
            throw new ChangeNoPermissionException(ChangeOperationType.STARTCHANGE.getText());
        }
        /** 开始变更 **/
        changeService.startChangeById(changeId, jsonObj.getString("source"));
        return null;
    }

}
